package cn.genmer.test.security.recordlog.util;

import com.google.common.base.Objects;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.springframework.util.ReflectionUtils;

import java.util.List;
import java.util.Map;

/**
 * @description: 对象工具类
 * @author: yyq
 * @date: 2023/8/28 10:48
 */
public abstract class ObjectUtils {

    /**
     * 获取更改字段
     *
     * @param before
     * @param after
     * @return
     */
    public static List<String> getDifferentFieldName(Object before, Object after) {
        List<String> diffList = Lists.newArrayList();
        if (before == null || after == null) {
            return diffList;
        }
        if (!before.getClass().isAssignableFrom(after.getClass())) {
            return diffList;
        }
        Map<String, Object> beforeFieldMap = Maps.newHashMap();
        ReflectionUtils.doWithLocalFields(before.getClass(), field -> {
            field.setAccessible(true);
            beforeFieldMap.put(field.getName(), field.get(before));
        });
        Map<String, Object> afterFieldMap = Maps.newHashMap();
        ReflectionUtils.doWithLocalFields(after.getClass(), field -> {
            field.setAccessible(true);
            afterFieldMap.put(field.getName(), field.get(after));
        });
        beforeFieldMap.forEach((k, beforeFileValue) -> {
            Object afterFileValue = afterFieldMap.get(k);
            if (!Objects.equal(beforeFileValue, afterFileValue)) {
                diffList.add(k);
            }
        });
        return diffList;
    }
}
